package com.sjft.cloud.commons.support.xss;

import com.sjft.cloud.commons.support.xss.util.XssUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

@Slf4j
public class XssRequestBodyWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    @SneakyThrows
    public XssRequestBodyWrapper(HttpServletRequest request) {
        super(request);
        body = IOUtils.toByteArray(request.getInputStream());
    }

    @Override
    public BufferedReader getReader() throws IOException {
        Reader inputStreamReader = new InputStreamReader(getInputStream());
        return IOUtils.toBufferedReader(inputStreamReader);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        InputStream inputStream = new ByteArrayInputStream(XssUtil.cleanXSS(body));
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return inputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }
}
